#include "sgl_number.h"
#include "stdio.h"

int sgl_number_init(sgl_number_t *number, sgl_obj_t* parent, double value)
{
    sgl_obj_t* obj;
    if(parent == NULL) {
        return -1;
    }
    number->value = value;
    number->font = NULL;
    obj = &number->obj;
    obj->parent = parent;
    obj->obj_type = SGL_OBJ_NUMBER;
    obj->event_data = NULL;
    obj->ev_stat = SGL_EVENT_NORMAL;
    sgl_obj_add_src_act_list(obj);
    sgl_obj_add_dirty_list(obj);
    return 0;
}

sgl_obj_t* sgl_number_create(sgl_obj_t* parent, double value)
{
    int ret;
    sgl_number_t *number;
    if(parent == NULL) {
        return NULL;
    }
    number = (sgl_number_t *)sgl_alloc(sizeof(sgl_number_t));
    if(number == NULL)
        return NULL;
    ret = sgl_number_init(number, parent, value);
    if(ret) {
        return NULL;
    }
    return  &number->obj;
}

void sgl_number_set_font(sgl_obj_t* obj, sgl_font_t *font)
{
    sgl_number_t *number = container_of(obj, sgl_number_t, obj);
    number->font = font;
}

void sgl_number_set_value(sgl_obj_t* obj, double value)
{
    sgl_number_t *number = container_of(obj, sgl_number_t, obj);
    if(value != number->value) {
        number->value = value;
        sgl_obj_add_dirty_list(obj);
    }
}

void sgl_number_set_text_align(sgl_obj_t *obj, sgl_align_type_e align)
{
    sgl_number_t *number = container_of(obj, sgl_number_t, obj);
    number->align = align;
}

void sgl_number_draw(sgl_obj_t* obj)
{
    sgl_number_t *number = container_of(obj, sgl_number_t, obj);
    char text[65] = { '0', '\0' };
    sgl_int64_to_str(number->value, text);
    sgl_size_t _size;
    sgl_pos_t pos;
    sgl_widget_draw_rect(rect);
    sgl_surf_t *surf = sgl_draw_get_active_surf(obj);
    sgl_widget_buffer_valid(obj);
    if(obj->style.radius) {
        sgl_draw_buffer_clear(surf, obj->parent->style.body_color);
        sgl_draw_round_rect_solid(surf, rect, obj->style.radius, obj->style.body_color, obj->parent->style.body_color);
    }
    else {
        sgl_draw_buffer_clear(surf, obj->style.body_color);
    }
    if(number->font) {
        _size.w = sgl_text_width(number->font, text);
        _size.h = sgl_text_height(number->font);
        pos = sgl_get_align_pos(&obj->size, &_size, number->align);
        pos.x = sgl_widget_draw_ofs_x(pos.x);
        pos.y = sgl_widget_draw_ofs_y(pos.y);
        sgl_draw_font_string(surf, text, pos.x, pos.y, obj->style.text_color, obj->style.body_color, number->font); 
    }
    sgl_widget_draw_buffer_flush;
}
